package com.hnxxxy.oa.document.controller;


import com.hnxxxy.oa.document.fileRequest.FileVO;
import com.hnxxxy.oa.document.fileRequest.SearchTag;
import com.hnxxxy.oa.document.model.FileDO;
import com.hnxxxy.oa.document.service.FileService;
import com.hnxxxy.oa.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * <p>
 * 文件信息表 前端控制器
 * </p>
 *
 * @author housang
 * @since 2022-05-16
 */
@RestController
@RequestMapping({"/document/fileDO"})
@Api(
        value = "FileController",
        tags = {"文档模块"}
)
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private FileService fileService;

    public FileController() {
    }

    @PostMapping({"/add"})
    @ApiOperation("增加文档")
    public R addFile(@ApiParam("文档对象") FileVO fileVO) {
        this.fileService.add(fileVO);
        return R.buildSuccess();
    }

    @PostMapping({"/show"})
    @ApiOperation("展示文档")
    public R showFile(@ApiParam("文档路径") String path) {
        List<FileDO> fileDOS = this.fileService.search(path);
        return R.buildSuccess(fileDOS);
    }

    @PostMapping({"/search"})
    @ApiOperation("展示搜索文档")
    public R searchFile(@ApiParam("搜索条件对象") SearchTag searchTag) {
        List<FileDO> fileDOS = this.fileService.fileSearch(searchTag);
        return R.buildSuccess(fileDOS);
    }

    @PostMapping({"/recycle/{id}"})
    @ApiOperation("删除文档")
    public R recycleFile(@ApiParam(value = "文档id",required = true) @PathVariable("id") int id) {
        this.fileService.recycle(id);
        return R.buildSuccess("文档进入回收站成功");
    }

    @PostMapping({"/delete{id}"})
    @ApiOperation("完全删除文档")
    public R deleteFile(@ApiParam(value = "文档id",required = true) @PathVariable("id") int id) {
        this.fileService.delete(id);
        return R.buildSuccess("文档完全删除成功");
    }

    @PostMapping({"/update/{id}"})
    @ApiOperation("修改文档")
    public R updateFile(@ApiParam(value = "文档id",required = true) @PathVariable("id") int id, @ApiParam("文档对象") FileVO fileVO) {
        this.fileService.update(id, fileVO);
        return R.buildSuccess("文档修改成功");
    }

    @PostMapping({"/document/upload"})
    @ApiParam("上传文档")
    public R upload(@ApiParam("uPath") String uPath, @RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return R.buildError("文件为空");
            }

            String fileName = file.getOriginalFilename();
            log.info("上传的文件名为：" + fileName);
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.info("文件的后缀名为：" + suffixName);
            String path = uPath + fileName;
            File dest = new File((new File(path)).getAbsolutePath());
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            file.transferTo(dest);
            return R.buildSuccess("上传成功");
        } catch (IllegalStateException var8) {
            var8.printStackTrace();
        } catch (IOException var9) {
            var9.printStackTrace();
        }

        return R.buildSuccess("上传成功");
    }

    @PostMapping({"/document/batch"})
    public R handleFileUpload(@ApiParam("path") String path, HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;

        for(int i = 0; i < files.size(); ++i) {
            file = (MultipartFile)files.get(i);
            String filePath = path;
            File dest = new File(path);
            if (!dest.exists()) {
                dest.mkdirs();
            }

            if (file.isEmpty()) {
                return R.buildSuccess("第 " + i + " 个文件上传失败因为文件为空");
            }

            try {
                byte[] bytes = file.getBytes();
                stream = new BufferedOutputStream(new FileOutputStream(new File(filePath + file.getOriginalFilename())));
                stream.write(bytes);
                stream.close();
            } catch (Exception var10) {
                stream = null;
                return R.buildSuccess("第 " + i + " 个文件上传失败 ==> " + var10.getMessage());
            }
        }

        return R.buildSuccess("上传成功");
    }

    @PostMapping({"/document/download"})
    public R download(@ApiParam("path") String path, HttpServletResponse response) {
        try {
            File file = new File(path);
            String filename = file.getName();
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException var9) {
            var9.printStackTrace();
        }

        return R.buildSuccess(response);
    }
}
